package com.leps.nq.sys.controller;

import com.leps.nq.common.aspect.Log;
import com.leps.nq.common.enums.BusinessType;
import com.leps.nq.common.vo.R;
import com.leps.nq.common.vo.RBuilder;
import com.leps.nq.sys.entity.SysConfig;
import com.leps.nq.sys.service.ISysConfigService;
import com.leps.nq.tx.core.SysConfigs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 参数配置表 前端控制器
 * </p>
 *
 * @author hex
 * @since 2022-05-20
 */
@RestController
@RequestMapping("/sys/sys-config")
@Api(tags = "系统参数设置接口")
public class SysConfigController {
    @Autowired
    ISysConfigService configService;

    @GetMapping
    @ApiOperation("获取所有系统参数")
    public R<List<SysConfig>> list() {
        List<SysConfig> list = this.configService.list();
        return RBuilder.ok(list);
    }

    @GetMapping("/name/{configName}")
    @ApiOperation("根据参数名称获取系统参数")
    public R<SysConfig> getByName(@PathVariable String configName) {
        SysConfig one = this.configService.lambdaQuery().eq(SysConfig::getConfigName, configName).one();
        return RBuilder.ok(one);
    }

    @GetMapping("/key/{configKey}")
    @ApiOperation("根据参数键名获取系统参数")
    public R<SysConfig> getByKey(@PathVariable String configKey) {
        SysConfig one = this.configService.lambdaQuery().eq(SysConfig::getConfigKey, configKey).one();
        return RBuilder.ok(one);
    }

    @PutMapping
    @ApiOperation("修改系统参数值")
    @Log(title = "系统参数", businessType = BusinessType.UPDATE)
    public R<?> update(@RequestBody SysConfig config) {
        boolean b = this.configService.updateById(config);
        if(b) SysConfigs.loadSysConfigs();
        return RBuilder.ofBoolean(b);
    }

    @PostMapping
    @ApiOperation("添加系统参数")
    @Log(title = "系统参数", businessType = BusinessType.INSERT)
    public R<?> save(@RequestBody SysConfig config) {
        boolean keyUnique = this.configService.checkConfigKeyUnique(config.getConfigKey());
        if(!keyUnique) throw new RuntimeException("参数键名" + config.getConfigKey() + "已存在！");
        boolean b = this.configService.save(config);
        if(b) SysConfigs.loadSysConfigs();
        return RBuilder.ofBoolean(b);
    }

    @DeleteMapping
    @ApiOperation("删除系统参数(系统内置参数不会被删除)")
    @Log(title = "系统参数", businessType = BusinessType.DELETE)
    public R<?> remove(@RequestBody Long[] configIds) {
        this.configService.removeByIds(configIds);
        SysConfigs.loadSysConfigs();
        return RBuilder.ok();
    }
}
